import time
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views.decorators.csrf import csrf_exempt
from rest_framework import exceptions
from rest_framework.parsers import JSONParser, FormParser

from rest_framework.views import APIView
from rest_framework.authentication import BaseAuthentication
from apitest.models import UserInfo, UserToken
from apitest.utils.throttle import VisitThrottle

data_list = {
    1:{'name':'test1','age':18},
    2:{'name':'test2','age':19}
}

def md5(user):
    import hashlib
    ctime = str(time.time())
    m = hashlib.md5(bytes(user,encoding='UTF-8'))
    m.update(bytes(ctime,encoding='UTF-8'))
    return m.hexdigest()


class DataList(APIView):
    throttle_classes = [VisitThrottle]
    def get(self,request,*args,**kwargs):
        ret = {'code':1000,'msg':None,'data':None}
        try:
            ret['data'] = data_list
        except Exception as e:
            pass
        return JsonResponse(ret)

# 登录认证
class AuthView(APIView):
    authentication_classes = []
    # parser_classes = [JSONParser, FormParser, ]
    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(AuthView, self).dispatch(*args, **kwargs)

    def post(self,request,*args,**kwargs):
        print('post请求')
        ret = {'resCode':1000,'msg':'正常登陆'}
        print(request.data)
        try:
            user = request.data['username']
            ret['username'] = user
            passwd = request.data['password']
            print(user,passwd)
            obj = UserInfo.objects.filter(username=user,password=passwd).first()
            if not obj:
                ret['resCode'] = 1001
                ret['msg'] = '用户名或密码错误'
                return JsonResponse(ret)
            #获取用户权限分组
            type = obj.user_type
            ret['type'] = type
            # 生成token
            token = md5(user)
            ret['token'] = token
            UserToken.objects.update_or_create(user=obj,defaults={'Token':token})
        except Exception as e:
            ret['resCode'] = 1002
            ret['msg'] = '系统错误'
        return JsonResponse(ret)


class MenuView(APIView):

    def post(self,request,*args,**kwargs):
        ret = {'code': 1000, 'msg': '正常登陆'}

        return JsonResponse(ret)
